// SPDX-License-Identifier: GPL-3.0-or-later

import QtQuick
import QtQuick.Layouts
import QtQuick.Controls
import Fk
import Fk.Components.LunarLTK
import Fk.Pages.LunarLTK
import Fk.Components.Common

GraphicsBox {
  id: root

  property var selectedItem: []
  property int max: 0
  property int selectedNum: 0
  property string titleName: ""

  title.text: Util.processPrompt(titleName)
  // TODO: Adjust the UI design in case there are more than 7 cards
  width: photoRow.width + 10
  height: 300

  Row {
    id: photoRow
    anchors.top: parent.top
    anchors.topMargin: 30
    spacing: -45

    Repeater {
      id: photoRepeater
      model: ListModel {
        id: playerInfos
      }

      Photo {
        id: photo
        // scale: 0.65
        scale: selectedItem.some(data => data.id === model.id) ? 0.75 : 0.65 //选中的变大
        playerid: model.id
        general: model.general
        deputyGeneral: model.deputyGeneral
        role: model.role
        role_shown: model.role_shown
        seatNumber: model.seat
        state: "candidate"
        screenName: model.screenName
        kingdom: model.kingdom
        maxHp: model.maxHp
        hp: model.hp
        shield: model.shield
        chained: model.chained
        handcards: -1 //不显示手牌数和上限
        
        // 修改选择逻辑
        selectable: {
          // 如果没有选中任何角色
          if (selectedItem.length === 0) {
            // 只能选择伤害大于0的角色作为伤害来源
            return model.num > 0;
          } 
          // 如果已经选中了一个角色
          else {
            // 可以选择自己
            if (selectedItem[0].id === model.id) return true;
            
            // 修正: 当selectedNum等于max且选中角色伤害为1时，只能分配给伤害为0的角色
            if (selectedNum === max && selectedItem[0].num === 1) {
              return model.num === 0;
            }
            
            // 其他情况：可以分配给任何角色
            return true;
          }
        }
        
        opacity: selectable ? 1 : 0.5

        Behavior on scale { NumberAnimation { duration: 100 } }
        //Behavior on x { NumberAnimation { duration: 280 } }

        Image {//“已选”绿字
          visible: selectedItem.some(data => data.id === model.id)
          source: SkinBank.cardDir + "chosen"
          anchors.horizontalCenter: parent.horizontalCenter
          anchors.bottom: parent.bottom
          anchors.bottomMargin: 15
          scale: 1.5
        }

        Image {//头上的锁
          visible: model.num === 0 && !selectedItem.length
          source: AppPath + "/image/button/skill/locked.png"
          anchors.horizontalCenter: parent.horizontalCenter
          anchors.top: parent.top
          anchors.topMargin: -50
        }

        GlowText {//头上的伤害数，角色作为待选时显示
          anchors.top: parent.top
          anchors.topMargin: -50
          anchors.horizontalCenter: parent.horizontalCenter
          text: model.num
          visible: selectedItem.length && selectedItem[0] !== model
          font.family: Config.libianName
          font.pixelSize: 50
          font.bold: true
          color: "#FEF7D6"
          glow.color: "#845422"
          glow.spread: 0.8
        }

        GlowText {//显示文本
          anchors.centerIn: parent
          text: (selectedItem.length && selectedItem[0] !== model) ? Lua.tr("click to exchange one damage") : model.num
          visible: true
          font.family: Config.libianName
          font.pixelSize: (selectedItem.length && selectedItem[0] !== model) ? 30 : (90 + 20 * model.num)
          font.bold: true
          color: "#FEF7D6"
          glow.color: "#845422"
          glow.spread: 0.8
        }

        onSelectedChanged: {
          // 如果没有选中任何角色，选择当前角色作为伤害来源
          if (selectedItem.length === 0) {
            // 确保角色伤害大于0
            if (model.num > 0) {
              selectedItem = [model];
            } else {
              selected = false; // 伤害为0的角色不能被选为伤害来源
            }
          } 
          // 如果已经选中了一个角色，选择当前角色作为伤害目标
          else {
            // 选择自己则取消记录
            if (selectedItem[0].id === model.id) {
              selectedItem = [];
              return;
            }
            
            // 检查分配是否合法
            var canTransfer = true;
            
            // 修正: 当selectedNum等于max且选中角色伤害为1时，只能分配给伤害为0的角色
            if (selectedNum === max && selectedItem[0].num === 1 && model.num !== 0) {
              canTransfer = false;
            }
            
            if (canTransfer) {
              var i = selectedItem[0].num;
              var j = model.num;
              i--;
              if (i < 1) {
                selectedNum++;
              }
              if (j < 1) {
                selectedNum--;
              }              
              j++;
              playerInfos.setProperty(selectedItem[0].index, "num", i);
              playerInfos.setProperty(model.index, "num", j);
            }
            
            // 无论是否成功转移，都清空选中项
            selectedItem = [];
          }
        }
        
        Component.onCompleted: {
          this.visibleChildren[12].visible = false; // hide role
        }
      }
    }
  }

  Item {
    id: buttonArea
    anchors.fill: parent
    anchors.bottomMargin: 10
    height: 40

    Row {
      anchors.horizontalCenter: parent.horizontalCenter
      anchors.bottom: parent.bottom
      spacing: 8

      MetroButton {
        Layout.fillWidth: true
        text: Lua.tr("OK")
        enabled: true

        onClicked: {
          close();
          roomScene.state = "notactive";
          const idsNum = [];//结果
          for (let i = 0; i < playerInfos.count; i++) {
            const data = playerInfos.get(i);
            idsNum[i] = [data.id, data.num];
          }
          ClientInstance.replyToServer("", idsNum);
        }
      }

      MetroButton {
        enabled: true
        text: Lua.tr("un-chained")

        onClicked: {
          for (let i = 0; i < playerInfos.count; i++) {
            const data = playerInfos.get(i);
            data.num = 1;
            playerInfos.set(i, data);
          }
          selectedItem = [];
          selectedNum = 0;
        }
      }

      MetroButton {
        Layout.fillWidth: true
        text: Lua.tr("Cancel")
        enabled: true

        onClicked: {
          root.close();
          roomScene.state = "notactive";
          ClientInstance.replyToServer("", "");
        }
      }
    }
  }

  function loadData(data) {
    data[0].forEach(playerId => {
      const player = Lua.evaluate(
        `(function()
          local player = ClientInstance:getPlayerById(${playerId})
          return {
            id = player.id,
            general = player.general,
            deputyGeneral = player.deputyGeneral,
            screenName = player.player:getScreenName(),
            kingdom = player.kingdom,
            role = player.role,
            role_shown = (player.role_shown or false),
            seat = player.seat,
            maxHp = player.maxHp,
            hp = player.hp,
            shield = player.shield,
            chained = player.chained,
            num = 1,
          }
        end)()`
      );
      playerInfos.append(player);
    });
    max = data[1];
    titleName = data[2];
  }
}